<?php

namespace App\Http\Controllers;

use App\Parts;
use App\PartsBatch;
use App\PartsInventory;
use App\Storehouse;
use Illuminate\Http\Request;

class PartsBatchController extends Controller
{
    public function index()
    {
        $list   = Batch::orderby('code','asc')->paginate(10);
        $s_info = Storehouse::pluck('name','id');
        return view('batch.index', compact('list','s_info'));
    }

    public function addparts()
    {
        $list   = Batch::orderby('code','asc')->paginate(10);
        $s_info = Storehouse::pluck('name','id');
        $p_info = Parts::pluck('name','id');
        return view('batch.addparts',compact('list','s_info','p_info'));
    }

    public function store(Request $request, $id = '')
    {


        $data = $request->except('_token');

        try {
            if ($id) {
                Parts::whereId($id)->update($data);
            } else {
                for ($i=0;$i<count($data['part_id']);$i++){
                    $data1=[
                        'batch_code'=>$data['batch_code'],
                        'parts_id' => $data['part_id'][$i],
                        'number' => $data['num'][$i],
                    ];
                    PartsBatch::create($data1);
                }
            }
        } catch (\Exception $e) {

            return redirect()->back()->with('rs', ['flag' => 'error', 'msg' => '编辑失败']);
        }
        return redirect('parts')->with('rs', ['flag' => 'success', 'msg' => '编辑成功']);
    }

}
